<?php
namespace app\index\controller;

use app\common\model\Shops;
use think\captcha\Captcha;
use think\Controller;
use think\facade\Session;

class Index extends Base
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 用户登录
     * @return mixed
     */
    public function login()
    {

        if ($this->request->method() === "POST") {
            $captcha = new Captcha();
            $value = $this->request->post('vertify');
            if (!$captcha->check($value)) {
                return $this->error('验证码错误');
            }
            $username = trim($this->request->post('username'));
            $password = trim($this->request->post('password'));
            if ($username == '') {
                return $this->error('用户名不能为空！');
            }
            if ($password == '') {
                return $this->error('密码不能为空！');
            }
            $user = Shops::where('sp_username', $username)->field('sp_id,sp_username,sp_name,sp_password,sp_status,sp_login_time,sp_number,sp_login_ip')->find();
            if (!$user) {
                return $this->error('当前账号不存在！');
            }
            if (!password_verify($password, $user['sp_password'])) {
                return $this->error('密码输入错误！');
            }

            if ($user['sp_status'] == 0) {
                return $this->error('您的商户已被冻结，请联系管理人员！');
            }

            Session::set('sp_id', $user['sp_id'], 'index');
            Session::set('sp_number', $user['sp_number'], 'index');
            Session::set('sp_username', $user['sp_username'], 'index');
            Session::set('last_login', $user['sp_login_time'], 'index');
            Session::set('last_ip', $user['sp_login_ip'], 'index');
            //更新数据
            Shops::where('sp_id', $user['sp_id'])->update(['sp_login_time' => time(), 'sp_login_ip' => $this->request->ip()]);
            $this->create_log('登录', $this->request->url()); //管理日志

            return $this->success('登录成功！', url('index/index'));

        }
        return $this->fetch();
    }

    /**
     * 推出登录
     */
    public function logout()
    {
        Session::clear('index');
        return $this->success("退出成功", url('Index/login'), '', 2);
    }

    /**
     * 验证码生成
     * @return \think\Response
     */
    public function captcha()
    {
        $config = [
            'fontSize' => 40,
            'length' => 4,
            'useCurve' => false,
            'reset' => true,
            'expire' => 1800,
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }

    public function index()
    {
        $this->assign('menu', getMenuArr());
        $this->assign('navigation', 'admins_index');
        $this->assign('title', '管理员列表');
        return $this->fetch();
    }

    public function welcome()
    {

    }

    public function user()
    {
        return $this->fetch();
    }
}
